package com.novasoftware.novagooglemap.service;
/**
 * 
 */

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.novasoftware.novagooglemap.db.DataBaseBuilder;
import com.novasoftware.novagooglemap.infrastructure.entity.BaseEntity;

public class SQLLiteServiceBase<TEntity extends BaseEntity> {

	private Activity mActivity;
	
	private DataBaseBuilder<TEntity> mBuilder;
	
	public SQLLiteServiceBase(Activity activity,DataBaseBuilder<TEntity> builder)
	{
		mActivity = activity;
		mBuilder = builder;
	}

	public  ArrayList<TEntity> GetAll( ) {
		
		ArrayList<TEntity> lists = new ArrayList<TEntity>();
		SQLiteDatabase db =getDb();
		String[] columns = {"*"};
		Cursor query = db.query(mBuilder.table(), columns, null, null, null, null, "Id ASC");
		if(query != null){
			query.moveToFirst();
			while(!query.isAfterLast()){
				TEntity entity = mBuilder.build(query);
				lists.add(entity);
				query.moveToNext();
			}
		}
		return lists;
	}

	public  ArrayList<TEntity> WhereSelect(String selection,String[] selectionArg) {

		ArrayList<TEntity> lists = new ArrayList<TEntity>();
		SQLiteDatabase db =getDb();
		String[] columns = {"*"};
		Cursor query = db.query(mBuilder.table(), columns, selection, selectionArg, null, null, "Id ASC");
		if(query != null){
			query.moveToFirst();
			while(!query.isAfterLast()){
				TEntity entity = mBuilder.build(query);
				lists.add(entity);
				query.moveToNext();
			}
		}
		return lists;
	}

	public synchronized TEntity Save(TEntity entity) {
		SQLiteDatabase db = getDb();
		
		ContentValues values = mBuilder.deconstruct(entity);
		
		if(entity.Id== -1 || entity.Id<=0)
		{
			db.insert(mBuilder.table(), null, values);
		}
		else {
			String[] whereArgs = {""+entity.Id};
			int row_count = db.update(mBuilder.table(), values, "Id=?", whereArgs);
			
			if(row_count == 0){
				db.insert(mBuilder.table(), null, values);
			}
		}

		db.close();
		return null;
	}

	public synchronized Boolean Delete(TEntity entry) {
		SQLiteDatabase db = getDb();
		String[] whereArgs = {""+entry.Id};
		int count = db.delete(TEntity.DB_NAME, "Id = ?", whereArgs);
		db.close();
		
		if(count>0)
			return true;
		else 
			return false;
	}
	
	private SQLiteDatabase getDb(){
		return  mActivity.openOrCreateDatabase(TEntity.DB_NAME, Context.MODE_PRIVATE, null);
	}

}
